/**
 * IP 체크관련 Class
 * 
 * @author 기존함수 그대로 사용(KJH)
 * @version 1.0, 2012-03-08 
 * @fix([수정자]) [yyyy-mm-dd]: [수정 내용]
 *
 */

package com.ubst.smartad.common;

import java.util.*;
import java.io.*;

import com.ubst.smartad.common.FileUtil;

public class IpChecker
{
	public final static int STRONG = 0; //check strongly
	public final static int WEAK = 1; //check weakly
	public static boolean result = false; //
	
	private static IpSearcher searcher; //access control용
	
	/**
	 * setup user IP Check
  	 */
	public static boolean isSetupValidIP(String user_home, String serverName, String s )
	{
		String listPath = FileUtil.getFilePath(user_home)+"conf"+File.separator+serverName+File.separator+"setup_ip.list";
		try
		{
			IpChecker.load(listPath);

			return searcher.is(s);
		}
		catch(NullPointerException e)
		{
			return false;
		}
 	}

	/**
	 * user IP Check
  	 */
	public static boolean isValidIP(String user_home, String serverName, String s )
	{
		String listPath = FileUtil.getFilePath(user_home)+"conf"+File.separator+serverName+File.separator+"user_login_ip.list";
		try
		{
			IpChecker.load(listPath);

			return searcher.is(s);
		}
		catch(NullPointerException e)
		{
			return false;
		}
 	}

	/**
	 * admin IP Check
  	 */
	public static boolean isAdminIP(String user_home, String serverName, String s )
	{
		String listPath = FileUtil.getFilePath(user_home)+"conf"+File.separator+serverName+File.separator+"admin_ip.list";
		try
		{
			IpChecker.load(listPath);

			return searcher.is(s);
		}
		catch(NullPointerException e)
		{
			return false;
		}
 	}

	public static synchronized void load(String listPath)
	{
		searcher = new IpSearcher();
		Enumeration ips = getList(listPath);
		while( ips.hasMoreElements() )
		{
			searcher.put( (String)ips.nextElement() );
		}
	}

	/* ip list prop로 읽어오기 */
	public static Enumeration getList(String listPath)
	{
		Enumeration ret = null;		
		FileInputStream fin = null;
		try
		{
			fin = new FileInputStream( listPath );
			Properties prop = new Properties();		
			prop.load(fin);
			ret = prop.propertyNames();
		}
		catch ( FileNotFoundException e )
		{
			System.out.println("<!> can't find file "+ listPath );	
		}
		catch ( Exception e2 )
		{
			e2.printStackTrace();
		}
		finally
		{
			try{ fin.close(); } catch(Exception e) {}
		}
		return ret;			
	}

	/* ip list prop 저장하기 */
	public static boolean setList(String listPath, Properties prop)
	{	
		boolean ret = true;
		FileOutputStream fos = null;
		try
		{
			fos = new FileOutputStream( listPath );
			prop.store(fos,"these lists was modified by admin module, so don't modify manually!");
		}
		catch ( FileNotFoundException e )
		{
			System.out.println("<!> can't write file "+ listPath );
			ret = false;
		}
		catch ( Exception e2 )
		{
			e2.printStackTrace();
			ret = false;
		}
		finally
		{
			try{ fos.close(); } catch(Exception e) {}
		}
		return ret;	
	}

	public static void reload(String file)
	{
		searcher = null;
		load(file);
	}
	
}
